<?php

namespace app\admin\controller;

use app\admin\model\Config as ConfigModel;
use app\admin\model\Member as MemberModel;
use think\Controller;
use think\facade\Session;
use think\Validate;

class Publiz extends Controller {
    protected function initialize() {
        parent::initialize();

        $config = cache('db_config_data');
        if (!$config) {
            $config = ConfigModel::listConfig();
            cache('db_config_data', $config);
        }
        config($config, 'app');
        $this->assign('_theme_style', config('color_style'));
    }

    public function login() {
        if ($this->request->isPost()) {
            $validate = Validate::make([
                'name' => 'require',
                'password' => 'require'
            ]);

            $data = [
                'name' => input('name'),
                'password' => input('password')
            ];

            if (!$validate->check($data)) {
                $this->error('用户名或密码不能为空');
            }

            $result = MemberModel::login($data['name'], $data['password']);
            if ($result) {
                return $this->redirect(url('index/index'));

            } else {
                $this->error('用户名或密码错误');
            }
        } else {
            return $this->fetch();
        }
    }

    public function logout() {
        if (is_login()) {
            //todo:退出系统记录日志
            Session::clear();
            return $this->success('退出成功', url('login'));
        } else {
            return $this->redirect("publiz/login");
        }
    }
}